var gamejs = require('gamejs');
var turretjs = require("js/turret");

/**
 * Create a Turret object
 *
 * @param {Match} match The match where this object will work
 * @param {[number, number]} coords The radar's position, in format [x, y]
 */
var slowmotionTurret = exports.slowmotionTurret = function(match, coords) {
	slowmotionTurret.superConstructor.apply(this, arguments);
	
	this.startHealth = this.health = 1000;
    this.currentMatch = match;
    this.center = coords;
    this.level = 0;
    this.upgradeList = [
            { price: 20, radius: 65, resaleValue: 70, motionslow: 0.5 }, // livello 0
            { price: 15, radius: 80, resaleValue: 70, motionslow: 0.5 }, // livello 1
            { price: 15, radius: 110, resaleValue: 70, motionslow: 0.5 } // livello 2
    ];
	this.image = gamejs.image.load(config.dir.images + "turret.png");
    this.timeFromLastShoot = 1000;
    this.radius = this.image.getSize()[0]/2;
    var dims = this.image.getSize();
};

/**
 * slowmotionTurret extends Turret
 */
gamejs.utils.objects.extend(slowmotionTurret, turretjs.Turret);

/**
 * Updates the position of the detector ray of the turret.
 *
 * @param {number} msDuration The time past from the last call, in milliseconds
 */
slowmotionTurret.prototype.update = function(msDuration) {
	this.timeFromLastShoot += msDuration;
	if(this.timeFromLastShoot > 1000) {
		var enemy_seen;
        var cur_center =  this.center;
        var cur_radius = this.upgradeList[this.level].radius;
        this.currentMatch.getMap().getEnemies().sprites().forEach(function(enemy) {
        	if(Math.sqrt(
					(enemy.getCoordinates()[0] - cur_center[0])*(enemy.getCoordinates()[0] - cur_center[0]) +
					(enemy.getCoordinates()[1] - cur_center[1])*(enemy.getCoordinates()[1] - cur_center[1])
			) < cur_radius){
        		enemy.slowdown(5);
        	}
        });    
        this.timeFromLastShoot = 0;
	}
};

/**
 * Draws the turret in the given Surface
 *
 * @param {gamejs.Surface} surface The Surface where draw on
 */
slowmotionTurret.prototype.draw = function(surface) {
	//draw turret tower
	var dim = this.image.getSize();
	var upLeft = gamejs.utils.vectors.subtract(this.center, gamejs.utils.vectors.divide(dim, 2));
	surface.blit(this.image, upLeft);
    
	//healt bar
	var startLine = gamejs.utils.vectors.subtract(this.center, gamejs.utils.vectors.divide([dim[0], dim[1] *3/2], 2));
	var endLine = gamejs.utils.vectors.add(startLine, [dim[0] *  this.health /this.startHealth, 0]);
	gamejs.draw.line(surface, '#adff2f', startLine, endLine, 2);
	
    //draw wave
    gamejs.draw.circle(surface, '#FFFFFF', this.center, this.upgradeList[this.level].radius*(this.timeFromLastShoot+1) / 1000, 1);
};